package com.report.conversion.listener;

import com.report.conversion.utils.DataSourceUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;

/**
 * 项目启动后初始化所有的数据源，放到全局环境变量中
 * @author: kevin wu
 * @date: 2023年03月14日 14:45
 */
@Component
public class ApplicationStartedListener  implements CommandLineRunner {

    @Autowired
    DataSource dataSource;

    @Autowired
    DataSourceUtils dataSourceUtils;
    @Override
    public void run(String... args) throws Exception {

        Connection connection = dataSource.getConnection();
        PreparedStatement ps = connection.prepareStatement("SELECT datasourceId,datasourceDriver,datasourceUrl,datasourceUserName,datasourcePassword FROM datasource");
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            HashMap dsMap = new HashMap();
            dsMap.put("driver",rs.getString("datasourceDriver"));
            dsMap.put("url",rs.getString("datasourceUrl"));
            dsMap.put("username",rs.getString("datasourceUserName"));
            dsMap.put("password",rs.getString("datasourcePassword"));
            dataSourceUtils.initDataSources(rs.getString("datasourceId"),dsMap);
        }
        connection.close();
    }
}
